import 'dart:io';

import 'package:FiduMart/core/network/model/link_model_entity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:FiduMart/constants/color_constant.dart';
import 'package:FiduMart/core/utils/logger.dart';
import 'package:FiduMart/core/utils/pref_utils.dart';
import 'package:FiduMart/screen/webview/web_controller.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:version/version.dart';

import '../../core/network/RequestClient.dart';
import '../../core/network/information_newsDetail_entity.dart';
import '../../core/network/market_news_list_entity.dart';
import '../../core/network/model/base/base_model_entity.dart';

class Page1Controller extends GetxController with SingleGetTickerProviderMixin {

  final pref = Get.find<PrefUtils>();
  var clubPage = 1;

  Dio _dio = Dio();

  var auditIos = '1'.obs; //1-审核 ，2-审核通过
  var auditAndroidPassed = false; //true 审核通过


  var blues = [ColorConstant.blue_gradient_1, ColorConstant.blue_gradient_2];
  var oranges = [ColorConstant.colorFFFE8426, ColorConstant.colorFFEEC218];
  var purples = [ColorConstant.colorFFD215D9, ColorConstant.colorFF105BB5];

  var linkModels = <LinkModelEntity>[].obs;

  late WebController webController;

  var isAppInstalledD = false.obs;

  static const _channel = MethodChannel('com.chain.fmart/platform');

  //是否通过审核
  bool passAudit() {
    // return true;
    if (Platform.isIOS) {
      return auditIos.value == "2";
    } else {
      return auditAndroidPassed;
    }
  }

  // MiningController controllerdMiNi = Get.find<MiningController>();

  @override
  Future<void> onInit() async {
    super.onInit();
    _dio.interceptors.add(LogInterceptor(responseBody: true));

  }

  //检查审核、更新
  Future<void> checkApp() async {
    final url = "https://cdn.fidumart.com/fidu/faudit.json?cacheVersion=${DateTime.now().millisecondsSinceEpoch}";
    try {
      var response = await Dio().get(url);
      if (response.statusCode == 200) {
        var jsonData = response.data;

        //放开此处测试
        // var testJson = {
        //   "androidVersion":"1.0.0",       //审核通过后，修改此处版本号
        //   "iosVersion":"1.0.0",
        //   "androidAuditVersion":"1.0.0",  //送审时，修改此处版本号
        //   "iosAuditVersion":"1.0.0",
        //   "webCacheVersion":1
        // };


        // jsonData = testJson;

        // await checkApproval(jsonData);

        isAppInstalledD.value = await isAppInstalled("com.um.wallet");
        Logger.log("isAppInstalledD:${isAppInstalledD}");

        await fetchLink();
        webController = Get.put(WebController());
        await checkUpdate(jsonData);
      }
    } catch (e) {
      // Handle exceptions
    }
  }

  //检查更新
  Future<void> checkUpdate(Map<String, dynamic> jsonData) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String localVersion = packageInfo.version;
    Logger.log("-----当前接口IOS状态：$jsonData");
    Logger.log("-----本地版本IOS状态：$packageInfo");
    String remoteVersion =
        Platform.isIOS ? jsonData['iosVersion'] : jsonData['androidVersion'];

    String auditVersion = Platform.isIOS
        ? jsonData['iosAuditVersion']
        : jsonData['androidAuditVersion'];
    if (auditVersion == localVersion.toString() && kReleaseMode) {
      auditIos.value = "2";
    }
    if (!kReleaseMode) {
      auditAndroidPassed = true;
      auditIos.value = "2";
    }
    if (Platform.isAndroid &&
        auditVersion == localVersion.toString() &&
        kReleaseMode) {
      auditAndroidPassed = true;
    }
    var localWebCache = await pref.getWebCacheVersion();
    var remoteWebCache = jsonData['webCacheVersion'];
    // if (localWebCache != remoteWebCache) {
      // webviewController.dispose();
      await pref.setWebCacheVersion(remoteWebCache);
    // }

    if (chkVersion(remoteVersion, localVersion)) {
      launchAppStore();
    }
  }

  //版本判断
  bool chkVersion(String remote, String local) {
    var remoteVersion = Version.parse(remote);
    var localVersion = Version.parse(local);
    Logger.log(
        'remoteVersion:${remoteVersion}' + ',localVersion:${localVersion}');
    return remoteVersion > localVersion;
  }

  Future<void> launchAppStore() async {
    final String url = Platform.isIOS
        ? 'https://apps.apple.com/app/id6478839344'
        : 'https://play.google.com/store/apps/details?id=com.um.market';
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {}
    exit(0);
  }

  var newsList = <MarketNewsListEntity>[].obs;
  Future getNewsList()async{
    try {
      var apiName = "/um/web/information/news/list";

      var response = await RequestClient().get(apiName,{
        "typeId":1001 //typeId=1001 白色app中心化，typeId=1002 黑色app去中心化
      },true);
      // var responseEntity =
      // BaseModelEntity<List<BalanceDRNBillEntity>>.fromJson(response);
      // billList.value = responseEntity.data!;

      List<MarketNewsListEntity> billList = (response["result"] as List)
          .map((e) => MarketNewsListEntity.fromJson(e))
          .toList();

      newsList.value = billList;
      return billList;
    } catch (e) {
      throw e;
    }
  }

  Future fetchLink() async {
    try {
      var url = 'https://cdn-yunying.utonmos.com/Exchanges/applink.json?cacheVersion=${DateTime.now().millisecondsSinceEpoch}';
      final response = await _dio.get(url);
      linkModels.value = (response.data as List)
          .map((e) => LinkModelEntity.fromJson(e))
          .toList();
    } catch (e) {
      print(e);
      throw Exception('Failed to load fetchLink');
    }
  }

  Future<bool> isAppInstalled(String packageName) async {
    // 这里添加平台特定的实现
    bool isInstalled = await _channel.invokeMethod('isAppInstalled', packageName);
    return isInstalled;
  }


}
